package com.jy.adscm.security.controller;

import com.jy.adscm.annotation.AdscmLogger;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.security.service.SecurityLoginUserService;
import com.jy.adscm.security.support.SimpleResponse;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yyy
 * @ClassName AdscmSecurityController
 * @Description TODO
 * @date 2018/7/26 16:22
 */
@RestController
public class AdscmSecurityController {

    @Autowired
    SecurityLoginUserService securityLoginUserService;

    /**
     * 当需要身份认证时，跳转到这里，返回状态码及json的提示信息
     * HttpStatus.UNAUTHORIZED : 401  未授权
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(){
        return new SimpleResponse("401","访问的服务需要身份认证，请引导用户到登录页",null);
    }

//    @RequestMapping("/adscm/hello/{username}")
//    public String hello(@PathVariable String username){
//        return "hello : "+username;
//    }
//    @RequestMapping("/adscm/test")
//    @PreAuthorize("hasAuthority('admin')")
//    public SimpleResponse test() throws AdscmSystemException {
//
//        System.out.println("hhhhhhh");
//        return  new SimpleResponse("200","hhhhhhhh","哈哈哈哈");
//    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/adscm/logout")
    public SimpleResponse logout(HttpServletRequest request) throws AdscmSystemException {

        securityLoginUserService.logout(request);

        return  new SimpleResponse("200","登出成功",null);
    }
    /**
     * 当获取某个资源没有权限的时候
     *
     * @return
     */
    @RequestMapping("/authentication/noPermission")
    public SimpleResponse noPermission(HttpServletRequest request){
        String statusCode = (String)request.getAttribute("statusCode");
        String desc = (String)request.getAttribute("desc");

        if (!AdscmBaseUtils.getInstance().isNotEmpty(statusCode,null)){
            statusCode = "403";
        }
        if (!AdscmBaseUtils.getInstance().isNotEmpty(desc,null)){
            desc = "没有权限";
        }

        return  new SimpleResponse(statusCode,desc,null);
    }

}
